#include <linux/if_ether.h>
#include <linux/rhashtable.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <net/flow_offload.h>
#include <net/pkt_cls.h>
#include "nveth_flow_offload.h"
#include "nveth.h"

static const struct rhashtable_params nveth_flow_ht_params = {
	.head_offset = offsetof(struct nveth_flow_entry, node),
	.key_offset = offsetof(struct nveth_flow_entry, cookie),
	.key_len = sizeof(unsigned long),
	.automatic_shrinking = true,
};

static int
nveth_flow_set_ipv4_addr(struct nveth_priv *priv, struct nveth_foe_entry *foe,
		       struct nveth_flow_data *data, bool egress)
{
	//return mtk_foe_entry_set_ipv4_tuple(eth, foe, egress,
	//				    data->v4.src_addr, data->src_port,
	//				    data->v4.dst_addr, data->dst_port);
	return 0;
}

static int
nveth_flow_set_ipv6_addr(struct nveth_priv *priv, struct nveth_foe_entry *foe,
		       struct nveth_flow_data *data)
{
	//return mtk_foe_entry_set_ipv6_tuple(eth, foe,
	//				    data->v6.src_addr.s6_addr32, data->src_port,
	//				    data->v6.dst_addr.s6_addr32, data->dst_port);
	return 0;
}

static void
nveth_flow_offload_mangle_eth(const struct flow_action_entry *act, void *eth)
{
	void *dest = eth + act->mangle.offset;
	const void *src = &act->mangle.val;

	if (act->mangle.offset > 8)
		return;

	if (act->mangle.mask == 0xffff) {
		src += 2;
		dest += 2;
	}

	memcpy(dest, src, act->mangle.mask ? 2 : 4);
}

int nveth_foe_entry_set_vlan(struct nveth_priv *priv, struct nveth_foe_entry *entry,  int vid)
{
#if 0
	struct mtk_foe_mac_info *l2 = mtk_foe_entry_l2(eth, entry);

	switch (mtk_get_ib1_vlan_layer(eth, entry->ib1)) {
	case 0:
		entry->ib1 |= mtk_get_ib1_vlan_tag_mask(eth) |
			      mtk_prep_ib1_vlan_layer(eth, 1);
		l2->vlan1 = vid;
		return 0;
	case 1:
		if (!(entry->ib1 & mtk_get_ib1_vlan_tag_mask(eth))) {
			l2->vlan1 = vid;
			l2->etype |= BIT(8);
		} else {
			l2->vlan2 = vid;
			entry->ib1 += mtk_prep_ib1_vlan_layer(eth, 1);
		}
		return 0;
	default:
		return -ENOSPC;
	}
#endif
	return 0;
}


static int
nveth_flow_mangle_ports(const struct flow_action_entry *act,
		      struct nveth_flow_data *data)
{
	u32 val = ntohl(act->mangle.val);

	switch (act->mangle.offset) {
	case 0:
		if (act->mangle.mask == ~htonl(0xffff))
			data->dst_port = cpu_to_be16(val);
		else
			data->src_port = cpu_to_be16(val >> 16);
		break;
	case 2:
		data->dst_port = cpu_to_be16(val);
		break;
	default:
		return -EINVAL;
	}

	return 0;
}

static int
nveth_flow_mangle_ipv4(const struct flow_action_entry *act,
		     struct nveth_flow_data *data)
{
	__be32 *dest;

	switch (act->mangle.offset) {
	case offsetof(struct iphdr, saddr):
		dest = &data->v4.src_addr;
		break;
	case offsetof(struct iphdr, daddr):
		dest = &data->v4.dst_addr;
		break;
	default:
		return -EINVAL;
	}

	memcpy(dest, &act->mangle.val, sizeof(u32));

	return 0;
}

static int
nveth_flow_set_output_device(struct nveth_foe_entry *foe, struct net_device *dev)
{
	return 0;
}

static int
nveth_flow_offload_replace(struct nveth_priv *priv, struct flow_cls_offload *f)
{
	struct flow_rule *rule = flow_cls_offload_flow_rule(f);
	struct flow_action_entry *act;
	struct nveth_flow_data data = {};
	struct nveth_foe_entry foe;
	struct net_device *odev = NULL;
	struct nveth_flow_entry *entry;
	//int offload_type = 0;
	//int wed_index = -1;
	u16 addr_type = 0;
	u8 l4proto = 0;
	int err = 0;
	int i;

	if (rhashtable_lookup(&priv->flow_table, &f->cookie, nveth_flow_ht_params))
		return -EEXIST;

	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_META)) {
		struct flow_match_meta match;

		flow_rule_match_meta(rule, &match);
	} else {
		return -EOPNOTSUPP;
	}

	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) {
		struct flow_match_control match;

		flow_rule_match_control(rule, &match);
		addr_type = match.key->addr_type;
	} else {
		return -EOPNOTSUPP;
	}

	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) {
		struct flow_match_basic match;

		flow_rule_match_basic(rule, &match);
		l4proto = match.key->ip_proto;
	} else {
		return -EOPNOTSUPP;
	}

	switch (addr_type) {
	case 0:
		//offload_type = MTK_PPE_PKT_TYPE_BRIDGE;
		if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
			struct flow_match_eth_addrs match;

			flow_rule_match_eth_addrs(rule, &match);
			memcpy(data.eth.h_dest, match.key->dst, ETH_ALEN);
			memcpy(data.eth.h_source, match.key->src, ETH_ALEN);
		} else {
			return -EOPNOTSUPP;
		}

		if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) {
			struct flow_match_vlan match;

			flow_rule_match_vlan(rule, &match);

			if (match.key->vlan_tpid != cpu_to_be16(ETH_P_8021Q))
				return -EOPNOTSUPP;

			data.vlan_in = match.key->vlan_id;
		}
		break;
	case FLOW_DISSECTOR_KEY_IPV4_ADDRS:
		//offload_type = MTK_PPE_PKT_TYPE_IPV4_HNAPT;
		break;
	case FLOW_DISSECTOR_KEY_IPV6_ADDRS:
		//offload_type = MTK_PPE_PKT_TYPE_IPV6_ROUTE_5T;
		break;
	default:
		return -EOPNOTSUPP;
	}

	flow_action_for_each(i, act, &rule->action) {
		switch (act->id) {
		case FLOW_ACTION_MANGLE:
			//if (offload_type == MTK_PPE_PKT_TYPE_BRIDGE)
			//	return -EOPNOTSUPP;
			if (act->mangle.htype == FLOW_ACT_MANGLE_HDR_TYPE_ETH)
				nveth_flow_offload_mangle_eth(act, &data.eth);
			break;
		case FLOW_ACTION_REDIRECT:
			odev = act->dev;
			break;
		case FLOW_ACTION_CSUM:
			break;
		case FLOW_ACTION_VLAN_PUSH:
			if (data.vlan.num == 1 ||
			    act->vlan.proto != htons(ETH_P_8021Q))
				return -EOPNOTSUPP;

			data.vlan.id = act->vlan.vid;
			data.vlan.proto = act->vlan.proto;
			data.vlan.num++;
			break;
		case FLOW_ACTION_VLAN_POP:
			break;
		case FLOW_ACTION_PPPOE_PUSH:
			break;
		default:
			return -EOPNOTSUPP;
		}
	}

	if (!is_valid_ether_addr(data.eth.h_source) ||
	    !is_valid_ether_addr(data.eth.h_dest))
		return -EINVAL;

	//err = mtk_foe_entry_prepare(eth, &foe, offload_type, l4proto, 0,
	//			    data.eth.h_source, data.eth.h_dest);
	//if (err)
	//	return err;

	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PORTS)) {
		struct flow_match_ports ports;

		//if (offload_type == MTK_PPE_PKT_TYPE_BRIDGE)
		//	return -EOPNOTSUPP;

		flow_rule_match_ports(rule, &ports);
		data.src_port = ports.key->src;
		data.dst_port = ports.key->dst;
	} //else if (offload_type != MTK_PPE_PKT_TYPE_BRIDGE) {
		//return -EOPNOTSUPP;
	//}

	if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
		struct flow_match_ipv4_addrs addrs;

		flow_rule_match_ipv4_addrs(rule, &addrs);

		data.v4.src_addr = addrs.key->src;
		data.v4.dst_addr = addrs.key->dst;

		nveth_flow_set_ipv4_addr(priv, &foe, &data, false);
	}

	if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
		struct flow_match_ipv6_addrs addrs;

		flow_rule_match_ipv6_addrs(rule, &addrs);

		data.v6.src_addr = addrs.key->src;
		data.v6.dst_addr = addrs.key->dst;

		nveth_flow_set_ipv6_addr(priv, &foe, &data);
	}

	flow_action_for_each(i, act, &rule->action) {
		if (act->id != FLOW_ACTION_MANGLE)
			continue;

		//if (offload_type == MTK_PPE_PKT_TYPE_BRIDGE)
		//	return -EOPNOTSUPP;

		switch (act->mangle.htype) {
		case FLOW_ACT_MANGLE_HDR_TYPE_TCP:
		case FLOW_ACT_MANGLE_HDR_TYPE_UDP:
			err = nveth_flow_mangle_ports(act, &data);
			break;
		case FLOW_ACT_MANGLE_HDR_TYPE_IP4:
			err = nveth_flow_mangle_ipv4(act, &data);
			break;
		case FLOW_ACT_MANGLE_HDR_TYPE_ETH:
			/* handled earlier */
			break;
		default:
			return -EOPNOTSUPP;
		}

		if (err)
			return err;
	}

	if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
		err = nveth_flow_set_ipv4_addr(priv, &foe, &data, true);
		if (err)
			return err;
	}

	//if (offload_type == MTK_PPE_PKT_TYPE_BRIDGE)
	//	foe.bridge.vlan = data.vlan_in;

	if (data.vlan.num == 1) {
		if (data.vlan.proto != htons(ETH_P_8021Q))
			return -EOPNOTSUPP;

		nveth_foe_entry_set_vlan(priv, &foe, data.vlan.id);
	}

	err = nveth_flow_set_output_device(&foe, odev);
	if (err)
		return err;

	entry = kzalloc(sizeof(*entry), GFP_KERNEL);
	if (!entry)
		return -ENOMEM;

	entry->cookie = f->cookie;
	memcpy(&entry->data, &foe, sizeof(entry->data));

	//err = mtk_foe_entry_commit(eth->ppe[entry->ppe_index], entry);
	//if (err < 0)
	//	goto free;

	err = rhashtable_insert_fast(&priv->flow_table, &entry->node,
				     nveth_flow_ht_params);
	if (err < 0)
		goto clear;

	return 0;

clear:
	//mtk_foe_entry_clear(eth->ppe[entry->ppe_index], entry);
free:
	kfree(entry);
	return err;
}

static int
nveth_flow_offload_destroy(struct nveth_priv *priv, struct flow_cls_offload *f)
{
	struct nveth_flow_entry *entry;

	entry = rhashtable_lookup(&priv->flow_table, &f->cookie,
				  nveth_flow_ht_params);
	if (!entry)
		return -ENOENT;

	rhashtable_remove_fast(&priv->flow_table, &entry->node,
			       nveth_flow_ht_params);

	kfree(entry);

	return 0;
}

//TODO: statistic for each flow

static int
nveth_flow_offload_stats(struct nveth_priv *priv, struct flow_cls_offload *f)
{
	struct nveth_flow_entry *entry;
	//u32 idle;

	entry = rhashtable_lookup(&priv->flow_table, &f->cookie,
				  nveth_flow_ht_params);
	if (!entry)
		return -ENOENT;

	f->stats.lastused = jiffies;// - idle * HZ;

	if (entry->hash != 0xFFFF) {
		f->stats.pkts += 1;
		f->stats.bytes += 1;
	}

	return 0;
}

static DEFINE_MUTEX(nveth_flow_offload_mutex);

int nveth_flow_offload_cmd(struct nveth_priv *priv, struct flow_cls_offload *cls)
{
	int err;

	mutex_lock(&nveth_flow_offload_mutex);
	switch (cls->command) {
	case FLOW_CLS_REPLACE:
		err = nveth_flow_offload_replace(priv, cls);
		break;
	case FLOW_CLS_DESTROY:
		err = nveth_flow_offload_destroy(priv, cls);
		break;
	case FLOW_CLS_STATS:
		err = nveth_flow_offload_stats(priv, cls);
		break;
	default:
		err = -EOPNOTSUPP;
		break;
	}
	mutex_unlock(&nveth_flow_offload_mutex);

	return err;
}

static int
nveth_setup_tc_block_cb(enum tc_setup_type type, void *type_data, void *cb_priv)
{
	struct flow_cls_offload *cls = type_data;
	struct net_device *dev = cb_priv;
	struct nveth_priv *priv;

	priv = netdev_priv(dev);

	if (!tc_can_offload(dev))
		return -EOPNOTSUPP;

	if (type != TC_SETUP_CLSFLOWER)
		return -EOPNOTSUPP;

	return nveth_flow_offload_cmd(priv, cls);
}

static int
nveth_setup_tc_block(struct net_device *dev, struct flow_block_offload *f)
{
	//struct nveth_priv *priv = netdev_priv(dev);
	//struct mtk_eth *eth = mac->hw;
	static LIST_HEAD(block_cb_list);
	struct flow_block_cb *block_cb;
	flow_setup_cb_t *cb;

	if (f->binder_type != FLOW_BLOCK_BINDER_TYPE_CLSACT_INGRESS)
		return -EOPNOTSUPP;

	cb = nveth_setup_tc_block_cb;
	f->driver_block_list = &block_cb_list;

	switch (f->command) {
	case FLOW_BLOCK_BIND:
		block_cb = flow_block_cb_lookup(f->block, cb, dev);
		if (block_cb) {
			flow_block_cb_incref(block_cb);
			return 0;
		}
		block_cb = flow_block_cb_alloc(cb, dev, dev, NULL);
		if (IS_ERR(block_cb))
			return PTR_ERR(block_cb);

		flow_block_cb_incref(block_cb);
		flow_block_cb_add(block_cb, f);
		list_add_tail(&block_cb->driver_list, &block_cb_list);
		return 0;
	case FLOW_BLOCK_UNBIND:
		block_cb = flow_block_cb_lookup(f->block, cb, dev);
		if (!block_cb)
			return -ENOENT;

		if (!flow_block_cb_decref(block_cb)) {
			flow_block_cb_remove(block_cb, f);
			list_del(&block_cb->driver_list);
		}
		return 0;
	default:
		return -EOPNOTSUPP;
	}
}

int nveth_setup_tc(struct net_device *dev, enum tc_setup_type type, void *type_data)
{
	switch (type) {
	case TC_SETUP_BLOCK:
	case TC_SETUP_FT:
		return nveth_setup_tc_block(dev, type_data);
	default:
		return -EOPNOTSUPP;
	}
}

int nveth_offload_init(struct nveth_priv* priv)
{
	return rhashtable_init(&priv->flow_table, &nveth_flow_ht_params);
}

